package com.bytedance.improvingroad.widget

import android.util.Log
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bytedance.improvingroad.model.CardConfig

/**
 * Created by chenxiong
 * date 11/17/21
 */
class SlideCardLayoutManager: RecyclerView.LayoutManager() {
    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
        //ViewHolder回收复用
        if (recycler == null) {
            Log.e("cx", "recycler is null")
        }
        detachAndScrapAttachedViews(recycler!!)

        val itemCount = itemCount
        val bottomPos = if (itemCount < CardConfig.MAX_SHOW_COUNT) {
            0
        } else {
            itemCount - CardConfig.MAX_SHOW_COUNT
        }
        for (i in bottomPos until itemCount) {
            val view = recycler.getViewForPosition(i)
            addView(view)

            measureChildWithMargins(view, 0, 0)
            val widthSpace = width - getDecoratedMeasuredWidth(view)
            val heightSpace = height - getDecoratedMeasuredHeight(view)

            // 布局 ---draw -- onDraw ,onDrawOver, onLayout
            layoutDecoratedWithMargins(
                view, widthSpace / 2, heightSpace / 2,
                widthSpace / 2 + getDecoratedMeasuredWidth(view),
                heightSpace / 2 + getDecoratedMeasuredHeight(view)
            )
            var level = itemCount - i -1
            if (level > 0) {
                if (level < CardConfig.MAX_SHOW_COUNT -1) {
                    view.translationY = CardConfig.TRANS_Y_GAP * level
                    view.scaleX = 1-CardConfig.SCALE_GAP*level
                    view.scaleY = 1-CardConfig.SCALE_GAP*level
                } else {
                    view.translationY = CardConfig.TRANS_Y_GAP * (level - 1)
                    view.scaleX = 1-CardConfig.SCALE_GAP*(level-1)
                    view.scaleY = 1-CardConfig.SCALE_GAP*(level-1)
                }
            }
        }
    }
}